package com.learn.hidcode;

import org.apache.commons.codec.digest.DigestUtils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;

public class Test {
    private static void printResponseContent(HttpURLConnection connection) throws IOException {
        if (connection.getResponseCode() >= 200 && connection.getResponseCode() <= 299) {
            // 对于成功响应（HTTP 状态码 2xx），读取并打印响应正文
            try (BufferedReader in = new BufferedReader(
                    new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
                String inputLine;
                StringBuilder content = new StringBuilder();
                while ((inputLine = in.readLine()) != null) {
                    content.append(inputLine).append("\n");
                }
                System.out.println(content);
                System.out.println("Response Content:\n" + URLDecoder.decode(content.toString(), "ASCII"));
            }
        } else {
            // 对于非成功响应，读取并打印错误消息
            try (BufferedReader in = new BufferedReader(
                    new InputStreamReader(connection.getErrorStream(), StandardCharsets.UTF_8))) {
                String inputLine;
                StringBuilder errorMessage = new StringBuilder();
                while ((inputLine = in.readLine()) != null) {
                    errorMessage.append(inputLine).append("\n");
                }
                System.out.println("Error Response Content:\n" + errorMessage.toString());
            }
        }
    }

    public static void main(String[] args) throws IOException {

        String t_time = System.currentTimeMillis()/1000+"";
        String t_sign = "123456"+t_time;
        String uploadUrl = "http://3dg7wj531797.vicp.fun/ocr?time="+t_time+"&sign="+ DigestUtils.md5Hex(t_sign);

        System.out.println(uploadUrl);
        String filePath = "D:\\software\\QQFile\\3.png"; // 替换为你要上传的文件路径

        // 读取文件内容到字节数组
        byte[] fileContent = readFileToByteArray(filePath);

        // 构建 HTTP 请求
        URL url = new URL(uploadUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/octet-stream"); // 根据实际情况调整 Content-Type

        // 设置请求体长度
        connection.setFixedLengthStreamingMode(fileContent.length);

        // 开启输出流，准备写入请求体
        connection.setDoOutput(true);

        try (OutputStream outputStream = connection.getOutputStream()) {
            // 写入文件内容到请求体
            outputStream.write(fileContent);
            outputStream.flush();
        }

        // 获取响应状态码
        int responseCode = connection.getResponseCode();
        System.out.println("Response Code : " + responseCode);

        // 打印响应内容
        printResponseContent(connection);

        // 关闭连接
        connection.disconnect();
    }

    private static byte[] readFileToByteArray(String filePath) throws IOException {
        File file = new File(filePath);
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream((int) file.length());
        try (BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(file))) {
            byte[] buffer = new byte[1024];
            int length;
            while ((length = bufferedInputStream.read(buffer)) != -1) {
                byteArrayOutputStream.write(buffer, 0, length);
            }
        }
        return byteArrayOutputStream.toByteArray();
    }

}
